﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Data;
using System.ServiceModel;
using OpalisConsole.EndUserService;
using System.Threading;
using System.ComponentModel;

namespace OpalisConsole.Views.User_Imaging
{
    public partial class SoftwareValidation : Page
    {
        Popup officeApps;
        Popup selfInstall;
        Popup autoInstall;
        Popup cannotReinstall;

        internal bool closeAutoInstall;
        internal bool closeSelfInstall;
        internal bool closeCannotReinstall;

        internal int magicNumberAutoInstall = 0;
        internal int magicNumberSelfInstall = 0;
        internal int magicNumberCannotReinstall = 0;

        public SoftwareValidation()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.Current.Resources["Computer_ID"].Equals("Not Approved"))
            {
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/Registration", System.UriKind.Relative));
            }
            else
            {
                if (App.Current.Resources.Contains("DeveloperStatus"))
                {
                    if ((bool)App.Current.Resources["DeveloperStatus"]) 
                    {
                        LinkUseUSMT.Visibility = System.Windows.Visibility.Visible;
                        DeveloperStackPanel.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                txtSoftwareValidationHeader.Text = "Software";
                txtSoftwareValidationDescription.Text = "All General Mills Windows 7 computers come with the following software:";

                txtSoftwareBlock.Text = "Your computer will be customized with the following software:";
                txtSoftwareWarning.Text = "If you have a business critical application that is missing from the list below do not continue.\n" +
                                          "Contact your local support for assistance.";

                txtSoftwareValidationDeveloper.Text = "As a General Mills Developer you will recieve a customized version of Windows 7 with the following software:";

                busyIndicatorSoftwareList.IsBusy = true;
                busyIndicatorSoftwareList.BusyContent = "Loading your software information";

                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getSoftwareDataCompleted += new EventHandler<getSoftwareDataCompletedEventArgs>(proxy_getSoftwareDataCompleted);
                proxy.getSoftwareDataAsync(App.Current.Resources["UserID"].ToString(),App.Current.Resources["UserDomain"].ToString());
            }
        }

        void proxy_getSoftwareDataCompleted(object sender, getSoftwareDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                busyIndicatorSoftwareList.IsBusy = false;
                System.Collections.ObjectModel.ObservableCollection<SoftwareData> SortedList = new System.Collections.ObjectModel.ObservableCollection<SoftwareData>();
                
                Dictionary<String, SoftwareData> keyListAuto = new Dictionary<String, SoftwareData>();
                Dictionary<String, SoftwareData> keyListSelf = new Dictionary<String, SoftwareData>();
                Dictionary<String, SoftwareData> keyListCannot = new Dictionary<String, SoftwareData>();
                
                foreach (SoftwareData data in e.Result)
                {
                    if (data.Status.Equals("Cannot be Reinstalled"))
                    {
                        keyListCannot.Add(data.PackageName, data);
                    }
                    if (data.Status.Equals("Automatically Installed"))
                    {
                        keyListAuto.Add(data.PackageName, data);
                    }
                    if (data.Status.Equals("Self Install"))
                    {
                        keyListSelf.Add(data.PackageName, data);
                    }
                }

                var itemsAuto = from k in keyListAuto.Keys
                    	        orderby keyListAuto[k] ascending
	                            select k;
                var itemsManual = from k in keyListSelf.Keys
                    	        orderby keyListSelf[k] ascending
	                            select k;
                var itemsCannot = from k in keyListCannot.Keys
                    	        orderby keyListCannot[k] ascending
	                            select k;
                              
                foreach(String key in keyListCannot.Keys)
                {
                    SortedList.Add(keyListCannot[key]);
                }
                foreach (String key in keyListSelf.Keys)
                {
                    SortedList.Add(keyListSelf[key]);
                }
                foreach (String key in keyListAuto.Keys)
                {
                    SortedList.Add(keyListAuto[key]);
                }

                gridSoftwareValidation.ItemsSource = SortedList;
            }
        }
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (App.Current.Resources.Contains("DeveloperStatus"))
            {
                if ((bool)App.Current.Resources["DeveloperStatus"])
                {
                    this.NavigationService.Navigate(new System.Uri("/User_Imaging/UseUSMT", System.UriKind.Relative));
                }
                else
                {
                    this.NavigationService.Navigate(new System.Uri("/User_Imaging/Scheduling", System.UriKind.Relative));
                }
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/Scheduling", System.UriKind.Relative));
            }
            
        }

        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new System.Uri("/User_Imaging/LandingPage", System.UriKind.Relative));
        }

        private void gridSoftwareValidation_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGridRow row = e.Row;
            SoftwareData data = (SoftwareData)row.DataContext;

            switch (data.Status)
            {
                case "Automatically Installed":
                    e.Row.Foreground = new SolidColorBrush(Colors.Black);
                    break;
                case "Self Install":
                    e.Row.Foreground = new SolidColorBrush(Colors.Blue);
                    break;
                case "Cannot be Reinstalled":
                    e.Row.Foreground = new SolidColorBrush(Colors.Red);
                    break;
            }
        }

        private void officeSuiteListItem_MouseEnter(object sender, MouseEventArgs e)
        {
            ListBoxItem officesuite = (ListBoxItem) sender;
            officeApps = new Popup();
            officeApps.Child = new Controls.OfficeProgramsPopup();

            GeneralTransform gt = officeSuiteListItem.TransformToVisual(Application.Current.RootVisual);
            Point offset = gt.Transform(new Point(0, 0));

            officeApps.VerticalOffset = offset.Y - 35;
            officeApps.HorizontalOffset = offset.X + 175;
            officeApps.IsOpen = true;
        }
        private void officeSuiteListItem_MouseLeave(object sender, MouseEventArgs e)
        {
            officeApps.IsOpen = false;
        }

        private void SelfInstall_MouseEnter(object sender, MouseEventArgs e)
        {
            lock (this)
            {
                closeSelfInstall = false;
            }
            if (cannotReinstall != null) 
            { 
                if (cannotReinstall.IsOpen) 
                {
                    lock (this)
                    {
                        cannotReinstall.IsOpen = false; 
                    }
                } 
            }
            if (autoInstall != null) 
            { 
                if (autoInstall.IsOpen) 
                { 
                    lock(this)
                    {
                        autoInstall.IsOpen = false; 
                    } 
                }
            }

            ListBoxItem obj = (ListBoxItem)sender;

            if (selfInstall == null)
            {
                selfInstall = new Popup();
                selfInstall.Child = new Controls.SelfInstallPopup();
                selfInstall.Child.MouseEnter += new MouseEventHandler(Child_MouseEnter);
                selfInstall.Child.MouseLeave += new MouseEventHandler(Child_MouseLeave);
            }

            GeneralTransform gt = obj.TransformToVisual(Application.Current.RootVisual);
            Point offset = gt.Transform(new Point(0, 0));

            selfInstall.VerticalOffset = offset.Y - 35;
            selfInstall.HorizontalOffset = offset.X + 175;
            lock (this)
            {
                selfInstall.IsOpen = true;
            }
        }
        private void AutoInstall_MouseEnter(object sender, MouseEventArgs e)
        {
            lock (this)
            {
                closeAutoInstall = false;
            }
            if (cannotReinstall != null) { if (cannotReinstall.IsOpen) { lock (this) { cannotReinstall.IsOpen = false; } } }
            if (selfInstall != null) { if (selfInstall.IsOpen) { lock(this) { selfInstall.IsOpen = false; } } }

            ListBoxItem obj = (ListBoxItem)sender;
            if (autoInstall == null)
            {
                autoInstall = new Popup();
                autoInstall.Child = new Controls.AutoInstallPopup();
            }

            GeneralTransform gt = obj.TransformToVisual(Application.Current.RootVisual);
            Point offset = gt.Transform(new Point(0, 0));

            autoInstall.VerticalOffset = offset.Y - 35;
            autoInstall.HorizontalOffset = offset.X + 175;
            lock (this)
            {
                autoInstall.IsOpen = true;
            }
        }
        private void NotReInstall_MouseEnter(object sender, MouseEventArgs e)
        {
            lock (this)
            {
                closeCannotReinstall = false;
            }
            if (autoInstall != null) { if (autoInstall.IsOpen) { lock (this) { autoInstall.IsOpen = false; } } }
            if (selfInstall != null) { if (selfInstall.IsOpen) { lock (this) { selfInstall.IsOpen = false; } } }

            ListBoxItem obj = (ListBoxItem)sender;

            if (cannotReinstall == null)
            {
                cannotReinstall = new Popup();
                cannotReinstall.Child = new Controls.CannotReinstallPopup();
            }

            GeneralTransform gt = obj.TransformToVisual(Application.Current.RootVisual);
            Point offset = gt.Transform(new Point(0, 0));

            cannotReinstall.VerticalOffset = offset.Y - 35;
            cannotReinstall.HorizontalOffset = offset.X + 175;
            lock (this)
            {
                cannotReinstall.IsOpen = true;
            }
        }
        private void Child_MouseEnter(object sender, MouseEventArgs e)
        {
            lock (this)
            {
                closeSelfInstall = false;
            }
        }

        private void AutoInstall_MouseLeave(object sender, MouseEventArgs e)
        {
            int internalMagicNumber = 0;
            lock (this)
            {
                magicNumberAutoInstall++;
                internalMagicNumber = magicNumberAutoInstall;

                closeAutoInstall = true;
            }
            BackgroundWorker bwAutoInstall = new BackgroundWorker();
            bwAutoInstall.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwAutoInstall_RunWorkerCompleted);
            bwAutoInstall.DoWork += new DoWorkEventHandler(bwSleep);
            bwAutoInstall.RunWorkerAsync(internalMagicNumber);
        }
        private void NotReInstall_MouseLeave(object sender, MouseEventArgs e)
        {
            int internalMagicNumber = 0;
            lock (this)
            {
                magicNumberCannotReinstall++;
                internalMagicNumber = magicNumberCannotReinstall;

                closeCannotReinstall = true;
            }
            BackgroundWorker bwNotReinstall = new BackgroundWorker();
            bwNotReinstall.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwNotReinstall_RunWorkerCompleted);
            //bwNotReinstall.DoWork += new DoWorkEventHandler(bwSleep);
            bwNotReinstall.DoWork += new DoWorkEventHandler(bwSleep);
            bwNotReinstall.RunWorkerAsync(internalMagicNumber);
        }
        private void SelfInstall_MouseLeave(object sender, MouseEventArgs e)
        {
            int internalMagicNumber = 0;
            lock (this)
            {
                magicNumberSelfInstall++;
                internalMagicNumber = magicNumberSelfInstall;

                closeSelfInstall = true;
            }   
            BackgroundWorker bwSelfInstall = new BackgroundWorker();
            bwSelfInstall.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSelfInstall_RunWorkerCompleted);
            bwSelfInstall.DoWork += new DoWorkEventHandler(bwSleep);
            bwSelfInstall.RunWorkerAsync(internalMagicNumber);
        }
        private void Child_MouseLeave(object sender, MouseEventArgs e)
        {
            lock (this)
            {
                magicNumberSelfInstall++;
                int internalMagicNumber = magicNumberSelfInstall;

                closeSelfInstall = true;

                BackgroundWorker bwSelfInstall = new BackgroundWorker();
                bwSelfInstall.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSelfInstall_RunWorkerCompleted);
                bwSelfInstall.DoWork += new DoWorkEventHandler(bwSleep);
                bwSelfInstall.RunWorkerAsync(internalMagicNumber);
            }
        }


        private void bwSleep(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(new TimeSpan(0, 0, 0, 2));
            e.Result = e.Argument;
        }

        private void bwNotReinstall_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (closeCannotReinstall && cannotReinstall.IsOpen && (int)e.Result == magicNumberCannotReinstall)
            {
                lock (this)
                {
                    cannotReinstall.IsOpen = false;
                }
            }
        }
        private void bwAutoInstall_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (closeAutoInstall && autoInstall.IsOpen && (int)e.Result == magicNumberAutoInstall)
            {
                lock (this)
                {
                    autoInstall.IsOpen = false;
                }
            }
        }
        private void bwSelfInstall_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (closeSelfInstall && selfInstall.IsOpen && (int)e.Result == magicNumberSelfInstall)
            {
                lock (this)
                {
                    selfInstall.IsOpen = false;
                }
            }
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            if (cannotReinstall != null)
            {
                if (cannotReinstall.IsOpen)
                {
                    lock (this)
                    {
                        cannotReinstall.IsOpen = false;
                    }
                }
            }
            if (autoInstall != null)
            {
                if (autoInstall.IsOpen)
                {
                    lock (this)
                    {
                        autoInstall.IsOpen = false;
                    }
                }
            }
            if (selfInstall != null)
            {
                if (selfInstall.IsOpen)
                {
                    lock (this)
                    {
                        selfInstall.IsOpen = false;
                    }
                }
            }
        }
    }
}
